package com.cloudlead.fleetAction.service.impl;

import com.cloudlead.common.lang.persistence.*;
import com.cloudlead.commonData.service.*;
import com.cloudlead.commonData.vo.*;
import com.cloudlead.fleetAction.service.FleetOrderSer;
import com.cloudlead.fleetAction.service.SendCarSer;
import com.cloudlead.fleetService.vo.SendCarVo;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by wyj on 2015/9/7.
 */
@Service
public class SendCarSerImpl implements SendCarSer {
    @Autowired
    TbContainerInfoService tbContainerInfoService;

    @Autowired
    TbFleetOrderService tbFleetOrderService;

    @Autowired
    TbCustomerOrderService tbCustomerOrderService;

    @Autowired
    BaseCarService baseCarService;

    @Autowired
    BaseDriverService baseDriverService;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    @Override
    @Transactional
    public String SendCarEdit(SendCarVo vo) {
        TbContainerInfo ci = tbContainerInfoService.view(vo.getContainerId());//查询箱信息

       if(ci != null){
            if(vo.getCarId()!=null&&!vo.getCarId().equals("")){//车辆ID不为空
                BaseCar bc = new BaseCar();
                    bc.setId(vo.getCarId());
                ci.setCar(bc);
            }
           if(vo.getDriverId()!=null&&!vo.getDriverId().equals("")){//驾驶员ID不为空
               BaseDriver bd = new BaseDriver();
               bd.setId(vo.getDriverId());
               ci.setDriver(bd);
           }
           if(vo.getTrailerDriverId()!=null&&!vo.getTrailerDriverId().equals("")){//甩挂驾驶员ID不为空
               BaseDriver bd = new BaseDriver();
               bd.setId(vo.getTrailerDriverId());
               ci.setTrailerDriver(bd);
           }
           if(vo.getTrailerCarId()!=null&&!vo.getTrailerCarId().equals("")){//甩挂车辆ID不为空
               BaseCar bc = new BaseCar();
               bc.setId(vo.getTrailerCarId());
               ci.setTrailerCar(bc);
           }
/*            if(vo.getContainerStatus()!=null&&(!"".equals(vo.getContainerStatus()))){//订单状态
                ci.setDestFleetStatus(vo.getContainerStatus());
            }*/
            ci.setFleetStatus(vo.getFleetStatus());//车状态
           TbContainerInfo tbContainerInfo= tbContainerInfoService.view(vo.getContainerId());
           TbFleetOrder tbFleetOrder=tbContainerInfo.getFleetOrder();
           TbCustomerOrder tbCustomerOrder=tbContainerInfo.getTbCustomerOrder();
           if(vo.getFleetStatus().equals("已派车")){
               DateTime date = new DateTime();
               vo.setSendCarTime(date);
               ci.setSendCarTime(vo.getSendCarTime());
           }

           if(!"未派车".equals(vo.getFleetStatus())&&!"已完成".equals(vo.getFleetStatus())){
               if(!"已执行".equals(tbFleetOrder.getOrderState())){
                   // 修改车队订单状态为已执行
                   tbFleetOrder.setOrderState("已执行");
                   tbFleetOrderService.update(tbFleetOrder);
               }
               if (tbCustomerOrder!=null) {
                   if ((!"已执行".equals(tbCustomerOrder.getPolOrderState())
                           && "0".equals(tbFleetOrder.getIsStart()))
                           ||
                           (!"已执行".equals(tbCustomerOrder.getDelOrderState())
                                   && "1".equals(tbFleetOrder.getIsStart())
                           )) {

                       if ("1".equals(tbFleetOrder.getIsStart())) {
                           tbCustomerOrder.setPolOrderState("已执行");

                       } else if ("0".equals(tbFleetOrder.getIsStart())) {
                           tbCustomerOrder.setDelOrderState("已执行");
                       }
                       tbCustomerOrderService.update(tbCustomerOrder);
                   }
               }

           }else if ((vo.getFleetStatus().equals("已完成"))) {
               List<TbContainerInfo> list_1=null;
               List<TbContainerInfo> list_2=null;
               //车队订单状态不等于已完成
               if (!"已完成".equals(tbFleetOrder.getOrderState())){
                   //查询该车队订单的所有箱子
                   list_1 = tbContainerInfoService.list(new Filter(new Criteria(new Term("fleetOrder.id", tbFleetOrder.getId()))), new Sort());
                   //查询该车队订单的所有已完成的箱子
                   List<Term> tr = new ArrayList<Term>();
                   tr.add(new Term("fleetOrder.id", tbFleetOrder.getId()));
                   tr.add(new Term("fleetStatus", "已完成"));//状态
                  list_2 = tbContainerInfoService.list(new Filter(new Criteria(tr)), new Sort());
                   if (list_1.size() == (list_2.size()+1)) {//所有箱子已完成
                       tbFleetOrder.setOrderState("已完成");//修改车队订单状态为已完成
                       tbFleetOrderService.update(tbFleetOrder);
                   }
             }
               //货主订单状态不等于已完成
               if (tbCustomerOrder!=null) {
                   if ((!"已完成".equals(tbCustomerOrder.getPolOrderState())
                           && "0".equals(tbFleetOrder.getIsStart()))
                           ||
                           (!"已完成".equals(tbCustomerOrder.getDelOrderState())
                                   && "1".equals(tbFleetOrder.getIsStart())
                           )) {
                       //查询该货主订单的所有箱子
                       list_1 = tbContainerInfoService.list(new Filter(new Criteria(new Term("tbCustomerOrder.id", tbCustomerOrder.getId()))), new Sort());
                       //查询该货主订单的所有已完成的箱子
                       List<Term> tr_1 = new ArrayList<Term>();
                       tr_1.add(new Term("tbCustomerOrder.id", tbCustomerOrder.getId()));
                       tr_1.add(new Term("fleetStatus", "已完成"));
                       tr_1.add(new Term("isStart", tbFleetOrder.getIsStart()));//进出口

                       list_2 = tbContainerInfoService.list(new Filter(new Criteria(tr_1)), new Sort());

                       if (list_1.size() == (list_2.size() + 1)) {//所有箱子已完成

                           if ("1".equals(tbFleetOrder.getIsStart())) {
                               //修改或者起始港车队执行状态为已完成
                               tbCustomerOrder.setPolOrderState("已完成");
                               tbCustomerOrderService.update(tbCustomerOrder);
                           } else if ("0".equals(tbFleetOrder.getIsStart())) {
                               //修改或者目的港车队执行状态为已完成
                               tbCustomerOrder.setDelOrderState("已完成");
                               tbCustomerOrderService.update(tbCustomerOrder);
                           }

                       }
                   }
               }
           }

            if(vo.getContainerWeight()>=0)//重量
                ci.setContainerWeight(vo.getContainerWeight());
            if(vo.getVolume()>=0)//体积
                ci.setVolume(vo.getVolume());
            if (vo.getComments()!=null&&!vo.getComments().equals(""))//备注
                ci.setComments(vo.getComments());
            if(vo.getContainerSeal()!=null&&!vo.getContainerSeal().equals(""))//铅封号
                ci.setContainerSeal(vo.getContainerSeal());
           if(vo.getType()!=null&& !vo.getType().equals(""))//尺寸类型
               ci.setType(vo.getType());
           //if(vo.getPackagingAddress()!=null&&!vo.getPackagingAddress().equals(""))//装箱地址
  //             ci.setPackagingAddress(vo.getPackagingAddress());
           //if(vo.getRemoveAddress()!=null&&(!"".equals(vo.getRemoveAddress())))//拆箱地址
 //              ci.setRemoveAddress(vo.getRemoveAddress());
           if(vo.getDangerous()!=null&&!vo.getDangerous().equals(""))//危险品标记
               ci.setDangerous(vo.getDangerous());
           else  ci.setDangerous(null);
           if(vo.getTrailerFlag()!=null&&!vo.getTrailerFlag().equals(""))//甩挂标记
               ci.setTrailerFlag(vo.getTrailerFlag());
           else  ci.setTrailerFlag(null);
           if(vo.getContainerNo()!=null&&!vo.getContainerNo().equals(""))//箱号
                ci.setContainerNo(vo.getContainerNo());

           if (vo.getPlanDate()!=null&&!vo.getPlanDate().equals("")) {//计划时间
               ci.setPlanDate(getDate(vo.getPlanDate()));//date 转换 dateTime 保存
            }

           if(vo.getSuitcaseTime()!=null&&!vo.getSuitcaseTime().equals("")) {//提箱时间
               ci.setSuitcaseTime(getDate(vo.getSuitcaseTime()));
           }else{
               ci.setSuitcaseTime(null);
           }
           if (vo.getIntoTime()!=null&&!vo.getIntoTime().equals("")) {//进入门点时间
               ci.setIntoTime(getDate(vo.getIntoTime()));
           }else{
               ci.setIntoTime(null);
           }
           if(vo.getOutTime()!=null&&!vo.getOutTime().equals("")) {//离开门点时间
               ci.setOutTime(getDate(vo.getOutTime()));
           }else{
               ci.setOutTime(null);
           }
           if(vo.getFinishTime()!=null&&!vo.getFinishTime().equals("")) {//完成时间
               ci.setFinishTime(getDate(vo.getFinishTime()));
           }else{
               ci.setFinishTime(null);
           }
           if(vo.getConfirmTime()!=null&&!vo.getConfirmTime().equals("")) {//确认时间
              ci.setConfirmTime(getDate(vo.getConfirmTime()));
           }
           if(vo.getFeedBack()!= null&&!vo.getFeedBack().equals("")) {//车队反馈信息
               ci.setFeedBack(vo.getFeedBack());
           }
           tbContainerInfoService.update(ci);
           if(!vo.getCarId().equals("")&&!vo.getDriverId().equals("")) {
               countCar(ci, vo);
               countDriver(ci, vo);
           }
           if(!vo.getTrailerCarId().equals("")&&!vo.getTrailerDriverId().equals("")) {
               countQryCar(ci, vo);
               countQryDriver(ci, vo);
           }
        }else{
            return "箱ID错误";
        }
        return "success";
    }

    private DateTime getDate(String sDate){
       Date d= null;
       try {
           d = sdf.parse(sDate);//string 转换 date
       } catch (ParseException e) {
           e.printStackTrace();
       }
       return new DateTime(d);//date 转换 dateTime 保存
    }
     //当前该车有多少任务数量
    public void countCar(TbContainerInfo ci,SendCarVo vo){
        if(!vo.getFleetStatus().equals("未派车")&&!vo.getFleetStatus().equals("已完成")) {
            TbContainerInfo tci = new TbContainerInfo();
            tci.setCar(ci.getCar());
            Criteria criteria = new Criteria();
            criteria.add(new Term("carId",tci.getCar().getId()));
            criteria.add(new Term("fleetStatus", Operator.NE, "未派车"));
            criteria.add(new Term("fleetStatus", Operator.NE, "已完成"));
            Filter filter = new Filter(criteria);
            List<TbContainerInfo> list = tbContainerInfoService.list(filter, null);
            BaseCar qryBc = baseCarService.view(tci.getCar().getId());
            qryBc.setOnlineTask(String.valueOf(list.size()));
            baseCarService.update(qryBc);
        }
        if(vo.getFleetStatus().equals("已完成")||vo.getFleetStatus().equals("未派车")){
            TbContainerInfo tci = new TbContainerInfo();
            tci.setCar(ci.getCar());

            Criteria criteria = new Criteria();
            criteria.add(new Term("carId",tci.getCar().getId()));
            criteria.add(new Term("fleetStatus", Operator.NE, "未派车"));
            criteria.add(new Term("fleetStatus", Operator.NE, "已完成"));
            Filter filter = new Filter(criteria);
            Long con = tbContainerInfoService.count(filter);
            BaseCar qryBc = baseCarService.view(tci.getCar().getId());
            qryBc.setOnlineTask(String.valueOf(con));
            baseCarService.update(qryBc);
        }
    }
   //当前该甩挂车有多少任务数量
    public void countQryCar(TbContainerInfo ci,SendCarVo vo){
        if(!vo.getFleetStatus().equals("未派车")&&!vo.getFleetStatus().equals("已完成")) {
            TbContainerInfo tci = new TbContainerInfo();
            tci.setTrailerCar(ci.getTrailerCar());
            Criteria criteria = new Criteria();
            criteria.add(new Term("trailerCarId",tci.getTrailerCar().getId()));
            criteria.add(new Term("fleetStatus", Operator.NE, "未派车"));
            criteria.add(new Term("fleetStatus", Operator.NE, "已完成"));
            Filter filter = new Filter(criteria);
            Long con = tbContainerInfoService.count(filter);
            BaseCar qryBc = baseCarService.view(tci.getTrailerCar().getId());
            qryBc.setOnlineTask(String.valueOf(con));
            baseCarService.update(qryBc);
        }
        if(vo.getFleetStatus().equals("已完成")||vo.getFleetStatus().equals("未派车")){
            TbContainerInfo tci = new TbContainerInfo();
            tci.setTrailerCar(ci.getTrailerCar());
            Criteria criteria = new Criteria();
            criteria.add(new Term("trailerCarId",tci.getTrailerCar().getId()));
            criteria.add(new Term("fleetStatus", Operator.NE, "未派车"));
            criteria.add(new Term("fleetStatus", Operator.NE, "已完成"));
            Filter filter = new Filter(criteria);
            Long con = tbContainerInfoService.count(filter);
            BaseCar qryBc = baseCarService.view(tci.getTrailerCar().getId());
            qryBc.setOnlineTask(String.valueOf(con));
            baseCarService.update(qryBc);
        }
    }
    //当前该驾驶员有多少任务数量
    public void countDriver(TbContainerInfo ci,SendCarVo vo){
        if(!vo.getFleetStatus().equals("未派车")&&!vo.getFleetStatus().equals("已完成")) {
            TbContainerInfo tci = new TbContainerInfo();
            tci.setDriver(ci.getDriver());
            Criteria criteria = new Criteria();
            criteria.add(new Term("driverId",tci.getDriver().getId()));
            criteria.add(new Term("fleetStatus", Operator.NE, "未派车"));
            criteria.add(new Term("fleetStatus", Operator.NE, "已完成"));
            Filter filter = new Filter(criteria);
            Long con = tbContainerInfoService.count(filter);
            BaseDriver qryBd = baseDriverService.view(tci.getDriver().getId());
            qryBd.setOnlineTask(String.valueOf(con));
            baseDriverService.update(qryBd);
        }
        if(vo.getFleetStatus().equals("已完成")||vo.getFleetStatus().equals("未派车")){
            TbContainerInfo tci = new TbContainerInfo();
            tci.setDriver(ci.getDriver());
            Criteria criteria = new Criteria();
            criteria.add(new Term("driverId",tci.getDriver().getId()));
            criteria.add(new Term("fleetStatus", Operator.NE, "未派车"));
            criteria.add(new Term("fleetStatus", Operator.NE, "已完成"));
            Filter filter = new Filter(criteria);
            Long con = tbContainerInfoService.count(filter);
            BaseDriver qryBd = baseDriverService.view(tci.getDriver().getId());
            qryBd.setOnlineTask(String.valueOf(con));
            baseDriverService.update(qryBd);
        }
    }
    //当前该甩挂驾驶员有多少任务数量
    public void countQryDriver(TbContainerInfo ci,SendCarVo vo){
        if(!vo.getFleetStatus().equals("未派车")&&!vo.getFleetStatus().equals("已完成")) {
            TbContainerInfo tci = new TbContainerInfo();
            tci.setTrailerDriver(ci.getTrailerDriver());
            Criteria criteria = new Criteria();
            criteria.add(new Term("trailerDriverId",tci.getTrailerDriver().getId()));
            criteria.add(new Term("fleetStatus", Operator.NE, "未派车"));
            criteria.add(new Term("fleetStatus", Operator.NE, "已完成"));
            Filter filter = new Filter(criteria);
            Long con = tbContainerInfoService.count(filter);
            BaseDriver qryBd = baseDriverService.view(tci.getTrailerDriver().getId());
            qryBd.setOnlineTask(String.valueOf(con));
            baseDriverService.update(qryBd);
        }
        if(vo.getFleetStatus().equals("已完成")||vo.getFleetStatus().equals("未派车")){
            TbContainerInfo tci = new TbContainerInfo();
            tci.setTrailerDriver(ci.getTrailerDriver());
            Criteria criteria = new Criteria();
            criteria.add(new Term("trailerDriverId",tci.getTrailerDriver().getId()));
            criteria.add(new Term("fleetStatus", Operator.NE, "未派车"));
            criteria.add(new Term("fleetStatus", Operator.NE, "已完成"));
            Filter filter = new Filter(criteria);
            Long con = tbContainerInfoService.count(filter);
            BaseDriver qryBd = baseDriverService.view(tci.getTrailerDriver().getId());
            qryBd.setOnlineTask(String.valueOf(con));
            baseDriverService.update(qryBd);
        }
    }
}
